package com.example.login;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {
	EditText un, pw;
	TextView error;
	Button ok;
	Button sender;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		un = (EditText) findViewById(R.id.et_un);
		pw = (EditText) findViewById(R.id.et_pw);
		ok = (Button) findViewById(R.id.btn_login);
		error = (TextView) findViewById(R.id.tv_error);
		sender = (Button) findViewById(R.id.btn_send);
		// set send button invisible and disabled
		sender.setVisibility(4);
		sender.setEnabled(false);

		ok.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("username", un
						.getText().toString()));
				postParameters.add(new BasicNameValuePair("password", pw
						.getText().toString()));

				String response = null;
				try {
					response = CustomHttpClient.executeHttpPost("http://titan.cmpe.boun.edu.tr:8086/VirtualWalks/androidlogin.htm", postParameters);
					String res = response.toString();
					res = res.replaceAll("\\s+", "");
					if(res.contains("true")){
					  int i= res.indexOf("firstName");
					  int j= res.indexOf("lastName");
					  res=res.substring(i+12, j-3);
					  error.setText("Welcome "+res+"");
						sender.setVisibility(0); // send button visible
						sender.setEnabled(true); // send button enable
					} else
						error.setText("Sorry!! Incorrect Username or Password");
				} catch (Exception e) {
					un.setText(e.toString());
				}

			}
		});
		sender.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent i = new Intent(Intent.ACTION_MAIN);
				PackageManager manager = getPackageManager();
				i = manager.getLaunchIntentForPackage("tv.ustream.ustream");
				i.addCategory(Intent.CATEGORY_LAUNCHER);
				startActivity(i);

			}
		});
	}
}
